const Router = require('koa-router');

const Article = require('../models/article')
const Tag = require('../models/tag')

let router = new Router({
  prefix: '/api'
})

// 新增文章
router.post('/article/add', async(ctx) => {
  const {
    title,
    desc,
    tag,
    state,
    cover,
    content
  } = ctx.request.body
  
  const article = await Article.create({
    title,
    desc,
    tag,
    state,
    cover,
    content,
    look: 0,
    createTime: Math.round(new Date())
  })
  if (article) {
    ctx.body = {
      code: 0,
      msg: '发布成功'
    }
  } else {
    ctx.body = {
      code: -1,
      msg: '发布失败'
    }
  }
})

// 删除文章
router.get('/article/del', async(ctx) => {
  const { id } = ctx.request.query
  try {
    const del = await Article.remove({"_id": id})
    if (del) {
      ctx.body = {
        code: 0,
        msg: '删除成功'
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '删除失败'
      }
    }
  } catch(err) {
    ctx.body = {
      code: -1,
      msg: '服务器异常'
    }
  }
})

// 更新文章
router.post('/article/update', async(ctx) => {
  const {
    id,
    title,
    desc,
    cover,
    state,
    content
  } = ctx.request.body
  let updataObj = {
    state: state
  }
  title && (updataObj.title = title)
  desc && (updataObj.desc = desc)
  cover && (updataObj.cover = cover)
  content && (updataObj.content = content)
  try {
    const article = await Article.updateOne({_id: id}, updataObj)
    if (article) {
      ctx.body = {
        code: 0,
        msg: '修改成功'
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '修改失败'
      }
    }
  } catch(err) {
    ctx.body = {
      code: -1,
      msg: '服务器异常'
    }
  }
})

// 管理查询文章列表
router.get('/article/admin/query', async(ctx) => {
  const {
    pageNo,
    limit
  } = ctx.request.query
  try {
    const result = await Article.find().limit(+limit).skip((pageNo - 1) * limit).sort({'createTime': -1})
    const count = await Article.count()
    ctx.body = {
      code: 0,
      data: {
        result,
        count
      }
    }
  } catch (err) {
    ctx.body = {
      code: -1,
      msg: '服务器异常'
    }
  }
})

// 管理查询文章详情
router.get('/article/admin/detail', async(ctx) => {
  const {
    id
  } = ctx.request.query
  const detail = await Article.findById(id)
  ctx.body = {
    code: 0,
    data: detail
  }
})

// 博客前端查询文章列表
router.get('/article/web/query', async(ctx) => {
  const {
    pageNo,
    limit
  } = ctx.request.query
  let result = await Article.find({state: true}, {content: 0}).limit(+limit).skip((pageNo - 1) * limit).sort({'createTime': -1})
  const tags = await Tag.find()

  await result.forEach(ri => {
    let tagName = []
    ri.tag.forEach(ti => {
      tagName.push(tags.filter(item => {
        return item._id == ti
      })[0].name)
    })
    ri.tag = tagName
  });
  const count = await Article.count({state: true})
  ctx.body = {
    code: 0,
    data: {
      result,
      count
    }
  }
})

// 博客前端查询文章详情
router.get('/article/web/detail', async(ctx) => {
  const {
    id
  } = ctx.request.query

  // 文章查看数加一
  await Article.findById(id).updateOne({$inc: {look: 1}})

  // 查询所有标签
  const tags = await Tag.find()

  // 查询文章详情
  const detail = await Article.findById(id)
  
  // 文章标签ID转换为标签名
  let tagName = []
  detail.tag.forEach(di => {
    tagName.push(tags.filter(item => {
      return item._id == di
    })[0].name)
  })
  detail.tag = tagName

  // 数据返回
  ctx.body = {
    code: 0,
    data: detail
  }
})

// 博客前端根据标签查询文章
router.get('/article/web/tag', async (ctx) => {
  const {tag} = ctx.request.query
  try {
    const tagId = await Tag.findOne({name: tag})
    const result = await Article.find({tag: String(tagId._id), state: true}, {content: 0}).sort({'createTime': -1})
    const tags = await Tag.find()
    await result.forEach(ri => {
      let tagName = []
      ri.tag.forEach(ti => {
        tagName.push(tags.filter(item => {
          return item._id == ti
        })[0].name)
      })
      ri.tag = tagName
    });
    if (result) {
      ctx.body = {
        code: 0,
        data: result
      }
    } else {
      ctx.body = {
        code: -1,
        msg:' 查询失败'
      }
    }
  } catch (err) {
    ctx.body = {
      code: -1,
      msg:' 服务器异常'
    }
  }
})

// 博客前端搜索文章
router.get('/article/web/search', async (ctx) => {
  const {
    title
  } = ctx.request.query
  try {
    const result = await Article.find({title: new RegExp(title), state: true}, {content: 0}).sort({'createTime': -1})
    if (result) {
      ctx.body = {
        code: 0,
        data: result
      }
    } else {
      ctx.body = {
        code: -1,
        msg: '查询失败'
      } 
    }
  } catch (err) {
    ctx.body = {
      code: -1,
      msg: '服务器异常'
    }
  }
})

module.exports = router